package com.redstar.interesting.common.starter.advice;

import com.redstar.interesting.common.constants.Constants;
import com.redstar.interesting.common.enums.EnumServerCode;
import com.redstar.interesting.common.response.JsonResponse;
import com.redstar.interesting.common.starter.annotations.ApiMethod;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author lihongxing
 */
@ControllerAdvice
public class JsonResponseAdvice implements ResponseBodyAdvice<Object> {



    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        //为啥设置返回头？
        response.getHeaders().add("trace-id", MDC.get(Constants.TRACE_ID));
        response.getHeaders().add("content-type", "application/json;charset=UTF-8");
        ApiMethod api = methodParameter.getMethodAnnotation(ApiMethod.class);
        if (api != null) {
            JsonResponse jsonResponse = new JsonResponse(EnumServerCode.SUCCESS.getCode());
            jsonResponse.setData(o);
            jsonResponse.setTraceId(MDC.get("traceId"));
            return jsonResponse;
        }
        return o;
    }


}
